package org.bedracket.pgeg.network;

import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import org.bedracket.pgeg.init.ModCapabilities;

import java.util.function.Supplier;

public class PlayerManaMessage{

    float mana;
    int maxMana;

    public PlayerManaMessage(float mana, int maxMana) {
        this.mana = mana;
        this.maxMana = maxMana;
    }

    public PlayerManaMessage(FriendlyByteBuf buf) {
        mana = buf.readFloat();
        maxMana = buf.readInt();
    }

    public static void buffer(PlayerManaMessage message, FriendlyByteBuf buf) {
        buf.writeFloat(message.mana);
        buf.writeFloat(message.maxMana);
    }

    public static void handler(PlayerManaMessage message, Supplier<NetworkEvent.Context> context) {
        if (context.get().getDirection() == NetworkDirection.PLAY_TO_CLIENT) {
            Player player = Minecraft.getInstance().player;
            if (player != null) {
                context.get().enqueueWork(() -> player.getCapability(ModCapabilities.PLAYER_MANA_LEVEL).ifPresent(
                        capability -> {
                            capability.setManaLevel(message.mana);
                            capability.setMaxManaLevel(message.maxMana);
                        }));
            }
            context.get().setPacketHandled(true);
        }
    }
}
